// api/request.js - 网络请求封装
import { getToken } from '../utils/storage.js';
import { mockApi } from './mock.js';

// 是否使用Mock数据
const USE_MOCK = true; // 开发环境下可以设置为true，生产环境下设置为false

// 基础URL配置
const BASE_URL = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:8000/api' 
  : 'http://h5.henanguanhao.com/api';

// 处理Mock请求
const handleMockRequest = (url, options) => {
  const method = options.method?.toUpperCase() || 'GET';
  
  // 任务相关Mock
  if (url.includes('/tasks') && method === 'GET') {
    if (url.includes('/detail')) {
      // 获取任务详情
      const taskId = url.split('/').pop();
      return mockApi.getTaskDetail(taskId);
    } else {
      // 获取任务列表
      return mockApi.getTasks(options.params || {});
    }
  }
  
  if (url.includes('/tasks/claim') && method === 'POST') {
    // 领取任务
    const taskId = options.data?.task_id;
    return mockApi.claimTask(taskId);
  }
  
  if (url.includes('/tasks/submit') && method === 'POST') {
    // 提交任务
    const taskId = options.data?.task_id;
    return mockApi.submitTask(taskId, options.data);
  }
  
  // 用户相关Mock
  if (url.includes('/user/info') && method === 'GET') {
    // 获取用户信息
    return mockApi.getUserInfo();
  }
  
  if (url.includes('/points/records') && method === 'GET') {
    // 获取积分记录
    return mockApi.getPointsRecords(options.params || {});
  }
  
  if (url.includes('/ranking/list') && method === 'GET') {
    // 获取排行榜
    return mockApi.getRankingList();
  }
  
  // 认证相关Mock
  if (url.includes('/auth/wx-login') && method === 'POST') {
    // 微信登录
    return mockApi.wxLogin(options.data?.code);
  }
  
  if (url.includes('/auth/phone-login') && method === 'POST') {
    // 手机号登录
    return mockApi.phoneLogin(options.data?.phone, options.data?.code);
  }
  
  return null;
};

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加认证token
  const token = getToken();
  if (token) {
    config.header = config.header || {};
    config.header['Authorization'] = `Bearer ${token}`;
  }
  
  // 添加时间戳防缓存
  if (config.method?.toUpperCase() === 'GET') {
    config.params = {
      ...config.params,
      _t: Date.now()
    };
  }
  
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  
  // 处理HTTP错误
  if (statusCode !== 200) {
    uni.showToast({
      title: `请求失败: ${statusCode}`,
      icon: 'none'
    });
    return Promise.reject(new Error(`HTTP Error: ${statusCode}`));
  }
  
  // 处理业务错误
  if (data.code !== 1) {
    uni.showToast({
      title: data.msg || '操作失败',
      icon: 'none'
    });
    
    // 处理登录失效
    if (data.code === 401) {
      // 清除token并跳转登录
      uni.clearStorageSync();
      // 此处可根据需要跳转到登录页面或显示登录弹窗
    }
    
    return Promise.reject(new Error(data.msg || 'Business Error'));
  }
  
  return data;
};

// 错误处理
const errorHandler = (error) => {
  console.error('Request Error:', error);
  
  // 处理网络错误
  if (!error.response) {
    uni.showToast({
      title: '网络连接失败，请检查网络设置',
      icon: 'none'
    });
  }
  
  return Promise.reject(error);
};

// 封装uni.request
export const request = (options) => {
  // 如果使用Mock数据，尝试匹配Mock API
  if (USE_MOCK) {
    const mockResponse = handleMockRequest(options.url, options);
    if (mockResponse) {
      return mockResponse;
    }
  }
  
  return new Promise((resolve, reject) => {
    // 应用请求拦截器
    const config = requestInterceptor(options);
    
    // 执行请求
    uni.request({
      ...config,
      url: BASE_URL + config.url,
      success: (response) => {
        try {
          const result = responseInterceptor(response);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (error) => {
        errorHandler(error);
        reject(error);
      }
    });
  });
};

// 封装常用请求方法
export const get = (url, params = {}, options = {}) => {
  return request({
    ...options,
    url,
    method: 'GET',
    params
  });
};

export const post = (url, data = {}, options = {}) => {
  return request({
    ...options,
    url,
    method: 'POST',
    data
  });
};

export const put = (url, data = {}, options = {}) => {
  return request({
    ...options,
    url,
    method: 'PUT',
    data
  });
};

export const del = (url, params = {}, options = {}) => {
  return request({
    ...options,
    url,
    method: 'DELETE',
    params
  });
};

// 文件上传封装
export const upload = (url, filePath, formData = {}, options = {}) => {
  // 如果使用Mock数据，直接返回成功
  if (USE_MOCK) {
    return Promise.resolve({
      code: 1,
      success: true,
      data: {
        url: 'https://example.com/uploads/' + Date.now() + '.jpg'
      }
    });
  }
  
  return new Promise((resolve, reject) => {
    const token = getToken();
    
    uni.uploadFile({
      ...options,
      url: BASE_URL + url,
      filePath,
      name: formData.name || 'file',
      formData,
      header: {
        ...options.header,
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (uploadFileRes) => {
        try {
          const response = JSON.parse(uploadFileRes.data);
          if (response.code === 1) {
            resolve(response);
          } else {
            uni.showToast({
              title: response.msg || '上传失败',
              icon: 'none'
            });
            reject(new Error(response.msg || 'Upload Error'));
          }
        } catch (error) {
          uni.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
          reject(error);
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '网络连接失败，请检查网络设置',
          icon: 'none'
        });
        reject(error);
      }
    });
  });
};

// 导出配置和方法
export default {
  request,
  get,
  post,
  put,
  delete: del,
  upload,
  USE_MOCK
};